package net.shopxx.runner;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import net.shopxx.Filter;
import net.shopxx.Filter.Operator;
import net.shopxx.constant.CollectConstant;
import net.shopxx.entity.Goods;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductImage;
import net.shopxx.entity.StockKeepingUnit;
import net.shopxx.entity.TaobaoProduct;
import net.shopxx.pager.Page;
import net.shopxx.pager.Pageable;
import net.shopxx.service.GoodsService;
import net.shopxx.service.ProductCategoryService;
import net.shopxx.service.ProductImageService;
import net.shopxx.service.TaobaoProductService;
import net.shopxx.util.FileUtils;

@Service("taobaoProductConvertRunner")
public class TaobaoProductConvertRunner implements Runnable {

	/** logger */
	private static final Logger logger = Logger.getLogger(TaobaoProductConvertRunner.class);
	@Resource(name = "productImageServiceImpl")
	private ProductImageService productImageService;
	@Resource(name = "goodsServiceImpl")
	private GoodsService goodsService;
	@Resource(name = "productCategoryServiceImpl")
	private ProductCategoryService productCategoryService;
	@Resource(name = "taobaoProductServiceImpl")
	private TaobaoProductService taobaoProductService;

	@Override
	public void run() {
		Pageable pageable = new Pageable();
		pageable.setPageSize(CollectConstant.DEFAULT_COLLECT_PAGE_SIZE);

		List<Filter> filters = new ArrayList<Filter>();
		Filter filter = new Filter();
		filter.setProperty(CollectConstant.TAOBAO_PRODUCT_STATUS_PROPERTY);
		filter.setOperator(Operator.eq);
		filter.setValue(CollectConstant.TAOBAO_PRODUCT_STATUS_INIT);
		filters.add(filter);

		pageable.setFilters(filters);
		List<TaobaoProduct> tps = null;

		do {
			Page<TaobaoProduct> page = taobaoProductService.findPage(pageable);

			tps = page.getContent();
			for (TaobaoProduct tp : tps) {

				try {
					
					Product product = new Product();
					
					String skuJson = tp.getSkuJson();
					List<StockKeepingUnit> skuList = getSku(skuJson, product);
					product.setStockKeepingUnit(skuList);
					
					List<ProductImage> productImages = null;
					try {
						productImages = dealWithTaobaoImg(tp);
					} catch (Exception e) {
						logger.error("图片处理错误：" + e);
						continue;
					}
					product.setProductImages(productImages);
					Collections.sort(product.getProductImages());
					if (product.getImage() == null && product.getMedium() != null) {
						product.setImage(product.getMedium());
					}

					product.setIsGift(false);
					product.setIsList(true);
					product.setIsMarketable(true);
					product.setIsTop(false);
					product.setIntroduction(tp.getIntroduction());
					BigDecimal price = BigDecimal.ZERO;
					BigDecimal marketPrice = BigDecimal.ZERO;
					JSONArray skuObjects = new JSONArray(tp.getSkuJson());
					Iterator<Object> it = skuObjects.iterator();
					while (it.hasNext()) {
						JSONObject skuObject = (JSONObject) it.next();
						// price小于等于0 或者 price比较大 price取相对小的值
						if (price.compareTo(BigDecimal.ZERO) != 1 || price.compareTo(skuObject.getBigDecimal("skuPrice")) == 1) {
							price = skuObject.getBigDecimal("skuPrice");
							marketPrice = skuObject.getBigDecimal("marketPrice");
						}
					}
					product.setPrice(price);
					product.setMarketPrice(marketPrice);
					product.setPoint(price.longValue());
					product.setProductCategory(productCategoryService.findRootById(CollectConstant.DEFAULT_PRODUCT_CATEGORY_ID));

					product.setName(tp.getTitle());
					product.setOutId(CollectConstant.TAOBAO_OUT_PREFIX + tp.getTaobaoProductId());
					product.setFullName(null);
					product.setAllocatedStock(0);
					product.setScore(0F);
					product.setTotalScore(0L);
					product.setScoreCount(0L);
					product.setHits(0L);
					product.setWeekHits(0L);
					product.setMonthHits(0L);
					product.setSales(0L);
					product.setWeekSales(0L);
					product.setMonthSales(0L);
					product.setWeekHitsDate(new Date());
					product.setMonthHitsDate(new Date());
					product.setWeekSalesDate(new Date());
					product.setMonthSalesDate(new Date());
					product.setReviews(null);
					product.setConsultations(null);
					product.setFavoriteMembers(null);
					product.setPromotions(null);
					product.setCartItems(null);
					product.setOrderItems(null);
					product.setGiftItems(null);
					product.setProductNotifies(null);
					Goods goods = new Goods();
					List<Product> products = new ArrayList<Product>();
					product.setGoods(goods);
					product.setSpecifications(null);
					product.setSpecificationValues(null);
					products.add(product);
					goods.getProducts().clear();
					goods.getProducts().addAll(products);
					goodsService.justSave(goods);

					tp.setStatus(CollectConstant.DEFAULT_TAOBAO_PRODUCT_STATUS_COLLECTED);
					taobaoProductService.update(tp);
					Thread.sleep(5000);
				} catch (Exception e) {
					logger.error("转换淘宝宝贝发生错误：" + e);
					break;
				}
			}
		} while (tps != null && tps.size() > 0);

	}

	private List<ProductImage> dealWithTaobaoImg(TaobaoProduct tp) throws Exception {
		List<ProductImage> pil = new ArrayList<ProductImage>();
		for (String img : tp.getImgs().split(";")) {
			ProductImage pi = new ProductImage();
			String tempFile = "upload_" + UUID.randomUUID() + ".tmp";

			FileUtils.download(img, tempFile, System.getProperty("java.io.tmpdir"));
			File file = new File(System.getProperty("java.io.tmpdir") + "/" + tempFile);

			pi.setFile(file);
			pi.setCollected(true);
			pi.setTitle(tp.getTitle());
			productImageService.build(pi);

			pil.add(pi);
		}

		return pil;
	}

	private List<StockKeepingUnit> getSku(String skuJson, Product product) {
		List<StockKeepingUnit> skuList = new ArrayList<StockKeepingUnit>();

		JSONArray jsonArray = new JSONArray(skuJson);
		for (int i = 0; i < jsonArray.length(); i++) {
			StockKeepingUnit sku = new StockKeepingUnit();
			JSONObject jsonNode = jsonArray.getJSONObject(i);
			sku.setSkuItem(jsonNode.getString("skuItem"));
			sku.setMarketPrice(jsonNode.getBigDecimal("marketPrice"));
			sku.setSkuPrice(jsonNode.getBigDecimal("skuPrice"));
			sku.setStockQuantity( 800 + (int)(Math.random()*100));
			sku.setProduct(product);
			skuList.add(sku);
		}
		return skuList;
	}

}
